package newui.page;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.AtlasActivity;
import com.shwread.android.qysw.activity.AtlasSeeActivity;
import com.shwread.android.qysw.activity.ImageTextActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.NewBookDetailActivity;
import com.shwread.android.qysw.activity.VideoDetailActivity;
import com.shwread.android.qysw10000000.R;
import com.shwread.android.ui.customview.BannerOnClickListener;
import com.shwread.android.ui.customview.QYViewPager;
import com.shwread.android.ui.customview.ViewPagerAdapter;
import com.shwread.android.ui.page.AbstractUIPage;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.httpsdk.constant.ResultCode;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.BannerInfo;
import logic.bean.BookInfo;
import logic.bean.ImageCollection;
import logic.bean.RegionContentItemBean;
import logic.bean.RegionModuleBean;
import logic.bean.SingleBook;
import logic.bean.SingleNews;
import logic.constants.DefaultConsts;
import newui.activity.EnterpriseModelContentActivity;
import newui.adapter.CagegoryViewPagerAdapter;
import newui.adapter.CategroyGridViewAdapter;
import newui.adapter.EnterpriseAdapter;
import newui.tools.DividerItemDecoration;
import newui.tools.FullyLinearLayoutManager;
import newui.view.IndicatorView;
import newui.view.MultiGridView;
import newui.view.WrapContentViewPager;
/**
 * .::::.
 * .::::::::.
 * :::::::::::  FUCK ,NO Bug any more,
 * ..:::::::::::'
 * '::::::::::::'
 * .::::::::::
 * '::::::::::::::..
 * ..::::::::::::.
 * ``::::::::::::::::
 * ::::``:::::::::'        .:::.
 * ::::'   ':::::'       .::::::::.
 * .::::'      ::::     .:::::::'::::.
 * .:::'       :::::  .:::::::::' ':::::.
 * .::'        :::::.:::::::::'      ':::::.
 * .::'         ::::::::::::::'         ``::::.
 * ...:::           ::::::::::::'              ``::.
 * ```` ':.          ':::::::::'                  ::::..
 * '.:::::'                    ':'````..
 */

/**
 * 学校项目，新的UI修改(企业动态)
 * Created by lex on 2017/7/6.
 */
public class EnterprisePage extends
        AbstractUIPage<MainActivity> {
    private static EnterprisePage instance;

    public static EnterprisePage getInstance(MainActivity t) {
        if (null == instance) {
            instance = new EnterprisePage(t);
        } else {
            instance.setActivity(t);
        }
        return instance;
    }

    public EnterprisePage(MainActivity t) {
        super(t);
    }

    public int ENTERPRISE_PAGE_SIZE = 8;//首页菜单单页显示数量
    private WrapContentViewPager enterpriseViewPager;
    private List<RegionModuleBean> enterpriseModeList;
    private IndicatorView enterpriseIndicatorView;
    private IndicatorView enterprise_head_points;

    private TextView tvTitle;
    private RecyclerView recyclerView;
    private EnterpriseAdapter adapter;

    //轮播图
    private QYViewPager vpPager;
    private LinearLayout llVp;
    private ViewPagerAdapter pagerAdapter;

    private View loadingView;
    private ImageView loadingImg;
    private AnimationDrawable animationDrawable;
    private PullToRefreshScrollView refreshView;

    private HashMap<Integer, View> views;
    private List<BannerInfo> banners;
    private boolean isLastSuccess = false;
    private ImageView ivPersion;

    public static final int IMAGE_COUNT = 5;
    //下部最新的十条数据
    private List<RegionContentItemBean> topContentList;

    private boolean isViewCreated = false;
    private List<View> viewList = null;
    private CagegoryViewPagerAdapter catAdapter = null;
    private int numColumns = 0;

    Runnable action = new Runnable() {
        @Override
        public void run() {
            int currentItem = vpPager.getCurrentItem();
            currentItem++;
            if (currentItem >= pagerAdapter.getCount()) {
                currentItem = 0;
            }
            vpPager.setCurrentItem(currentItem);
            //设置小圆点指示器的选中位置
            enterprise_head_points.setCurrentIndicator(currentItem - 2);//减2是因为图片数据源多加上了首尾两个
        }
    };

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) return curMyView;
        curMyView = bActivity.getLayoutInflater().inflate(R.layout.page_enterprise, null);
        initView();
        return curMyView;
    }

    void initView() {
        viewList = new ArrayList<View>();
        banners = new ArrayList<>();
        views = new HashMap<>();
        enterpriseModeList = new ArrayList<>();
        topContentList = new ArrayList<>();

        //设置标题栏
        tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
        tvTitle.setText(R.string.maintab_enter);
        ivPersion = (ImageView) curMyView.findViewById(R.id.common_header_persion);
        ivPersion.setVisibility(View.VISIBLE);
        ivPersion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bActivity.goPersonalActivity();
            }
        });

        loadingView = curMyView.findViewById(R.id.common_loading_layout);
        loadingImg = (ImageView) curMyView.findViewById(R.id.common_loading__img);
        refreshView = (PullToRefreshScrollView) curMyView.findViewById(R.id.refreshView);

        //顶部轮播图的设置
        vpPager = (QYViewPager) curMyView.findViewById(R.id.enterprise_head_pager);
        llVp = (LinearLayout) curMyView.findViewById(R.id.llVp);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) llVp.getLayoutParams();
        lp.height = DefaultConsts.BANNER_DEFAULT_HIGHT;
        lp.width = DefaultConsts.BANNER_DEFAULT_WIDTH;
        llVp.setLayoutParams(lp);
        enterprise_head_points = (IndicatorView) curMyView.findViewById(R.id.entIndicatorView);
        vpPager.setOnPageChangeListener(new PagerChangeListener());
        pagerAdapter = new ViewPagerAdapter(bActivity, views, new BannerClick());
        vpPager.setAdapter(pagerAdapter);
        enterpriseViewPager = (WrapContentViewPager) curMyView.findViewById(R.id.enterprise_vp);
        enterpriseIndicatorView = (IndicatorView) curMyView.findViewById(R.id.enterprise_indicator);
        //recycleView的一些配置
        recyclerView = (RecyclerView) curMyView.findViewById(R.id.recyclerView);
        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(bActivity);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(bActivity, LinearLayoutManager.VERTICAL));
        adapter = new EnterpriseAdapter(bActivity, topContentList);
        adapter.setOnRecyclerViewItemClickListener(new EnterpriseAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, Object data) {
                RegionContentItemBean contentItem = (RegionContentItemBean) data;
                String contentType = contentItem.getType();
                if (contentType.equalsIgnoreCase("1")) { //单条资讯
                    //todo 跳转到图文详情
                    SingleNews singleNews = contentItem.getSingleNews();
                    gotoImageTextActivity(singleNews.getHtmlUrl(), singleNews.getTitle(), singleNews.getModelContentDetailId() + "");
                } else if (contentType.equalsIgnoreCase("2")) {//多条资讯
                    //每个已经处理了， 这里不需要处理
                } else if (contentType.equalsIgnoreCase("3")) {//音频

                } else if (contentType.equalsIgnoreCase("4")) {//视频
                    gotoVideoDetailActivity(contentItem);
                } else if (contentType.equalsIgnoreCase("5")) { //图集
                    //todo 跳转到查看图集图片
                    gotoImageViewerActivity(contentItem);
                } else if (contentType.equalsIgnoreCase("6")) { //单本书籍
                    //跳转到书籍详情
                    SingleBook singleBook = contentItem.getSingleBook();
                    BookInfo bookInfo = singleBook.getBookInfo();
                    if (bookInfo == null) return;
                    //#ifdef SHOW_OLDBOOKDETAIL
                    //$ Intent intent = new Intent(bActivity, BookDetailActivity.class);
                    //#else
                    Intent intent = new Intent(bActivity, NewBookDetailActivity.class);
                    //#endif
                    bookInfo.setAuthor("");
                    intent.putExtra("BookInfo", bookInfo);
                    bActivity.startActivity(intent);
                }
            }
        });
        recyclerView.setAdapter(adapter);
        refreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (refreshView.isHeaderShown()) { //下拉刷新
                    refresh();
                }
            }
        });

        catAdapter = new CagegoryViewPagerAdapter(viewList);
        enterpriseViewPager.setAdapter(catAdapter);
        enterpriseViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                enterpriseIndicatorView.setCurrentIndicator(position);
            }
        });
        refresh();
    }

    private void refresh() {
        updateLoadingView(0);
        getModuleDatas();
        getViewPagerBanner();
        qryTopContentList();
    }

    @Override
    public int enter(IUIPage<?> arg0) {
        refreshView.scrollTo(0, 0);
//        if (!isLastSuccess) {
//            if (NetworkUtil.isNetAvailable(bActivity)) {
//                refresh();
//            } else {
//                new NoNetDialog(bActivity).show();
//            }
//        }
        return 0;
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle arg1) {

    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        return null;
    }


    private void initBannerView() {
        if (banners.size() == 0) {
            return;
        }
        vpPager.setCurrentItem(1);
        pagerAdapter.notifyDataSetChanged();
        startScroll();
    }

    private void startScroll() {
        if (banners.size() <= 1) {
            return;
        }
        vpPager.removeCallbacks(action);
        vpPager.postDelayed(action, DefaultConsts.BANNER_CHANGE_TIME);
    }

    public static void destroy() {
        if (instance != null) {
            instance.dispose();
            instance = null;
        }
    }

    @Override
    public void dispose() {
        isLastSuccess = false;
        if (null != banners) {
            banners.removeAll(banners);
        }
        super.dispose();
        if (null != vpPager && null != action) {
            vpPager.removeCallbacks(action);
        }
    }

    /**
     * Banner的滚动事件
     */
    private class PagerChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int i) {
            enterprise_head_points.setCurrentIndicator(i-1);
            int pageIndex = i;
            if (i == 0) {
                // 当视图在第一个时，将页面号设置为图片的最后一张。
                pageIndex = banners.size() - 2;
            } else if (i == banners.size() - 1) {
                // 当视图在最后一个是,将页面号设置为图片的第一张。
                pageIndex = 1;
            }
            if (i != pageIndex) {
                vpPager.setCurrentItem(pageIndex, false);
            }
            startScroll();
        }
    }

    private void getViewPagerBanner() {
        NewActionHelp.qryEnterpriseZoneBanner(bActivity, new ObjectHttpResponseHandler<List<BannerInfo>>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                refreshView.onRefreshComplete();
                Log.e("111111fail", "qryEnterpriseZoneBanner" + s);
                bActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        updateLoadingView(-1);
                    }
                });
                isLastSuccess = false;
            }

            @Override
            public void onSuccess(int i, Header[] headers, List<BannerInfo> bannerInfos, String s) {
                isLastSuccess = true;
                refreshView.onRefreshComplete();
                updateLoadingView(1);
                banners.clear();
                if (bannerInfos.size() > 1) {
                    //加上首位的图片，为了循环轮播
                    banners.add(bannerInfos.get(bannerInfos.size() - 1));
                    banners.addAll(bannerInfos);
                    banners.add(bannerInfos.get(0));
                } else {
                    banners = bannerInfos;
                }
                bActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        pagerAdapter.setData(banners);
                        initBannerView();
                    }
                });
                enterprise_head_points.setIndicatorCount(bannerInfos.size());
                enterprise_head_points.setCurrentIndicator(vpPager.getCurrentItem());
            }

            @Override
            public Type getType() {
                return new TypeToken<List<BannerInfo>>() {
                }.getType();
            }
        });
    }

    /**
     * Banner点击事件
     */
    private class BannerClick implements BannerOnClickListener {
        @Override
        public void click(BannerInfo info) {
            clickBanner(info);
        }
    }

    void clickBanner(BannerInfo info) {
        switch (info.getType()) {
            case BannerInfo.TYPE_BANNER:
                break;
            case BannerInfo.TYPE_BOOKS:
                break;
            case BannerInfo.TYPE_BOOKSURL:
                bActivity.goBookDetailActivity(info.getBooks());
                break;
            case BannerInfo.TYPE_URL:
                bActivity.goWebViewActivity(info);
                break;
        }
    }

    /**
     * @param flag 0:加载中，1：加载完成，-1：加载失败
     */
    private void updateLoadingView(int flag) {
        switch (flag) {
            case -1:
                loadingView.setVisibility(View.VISIBLE);
                refreshView.setVisibility(View.GONE);
                if (animationDrawable != null && animationDrawable.isRunning()) {
                    animationDrawable.stop();
                }
                loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
                break;
            case 0:
                loadingView.setVisibility(View.VISIBLE);
                refreshView.setVisibility(View.GONE);
                loadingImg.setBackgroundResource(R.drawable.home_progress);
                animationDrawable = (AnimationDrawable) loadingImg.getBackground();
                animationDrawable.start();
                break;
            case 1:
                loadingView.setVisibility(View.GONE);
                refreshView.setVisibility(View.VISIBLE);
                break;
        }
    }

    //获取模块分类的数据
    private void getModuleDatas() {
        NewActionHelp.qryModuleList(bActivity, 50, new ObjectHttpResponseHandler<List<RegionModuleBean>>() {
            @Override
            public void onFailure(int result, Header[] headers, String s, Throwable throwable) {
                Log.e("111111", "qryModuleList" + s);
                refreshView.onRefreshComplete();
                final String errMsg = ResultCode.getResultText(result);
                isLastSuccess = false;
            }

            @Override
            public void onSuccess(int i, Header[] headers, List<RegionModuleBean> regionModuleBeanList, String s) {
                isLastSuccess = true;
                refreshView.onRefreshComplete();
                Log.e("1111112", "qryModuleList" + s);
                if (null == regionModuleBeanList || regionModuleBeanList.size() == 0) {
                    enterpriseViewPager.setVisibility(View.GONE);
                    return;
                }
                enterpriseModeList.clear();
                enterpriseModeList.addAll(regionModuleBeanList);
                int pageCount = (int) Math.ceil(enterpriseModeList.size() * 1.0 / ENTERPRISE_PAGE_SIZE);
                if (pageCount > 1) {
                    enterpriseIndicatorView.setIndicatorCount(pageCount);
                    enterpriseIndicatorView.setCurrentIndicator(enterpriseViewPager.getCurrentItem());
                    enterpriseIndicatorView.setVisibility(View.VISIBLE);
                } else {
                    enterpriseIndicatorView.setVisibility(View.GONE);
                }
                int h1 = dp2px(bActivity, 75);
                int h2 = sp2px(bActivity, 15);
                int height = h1 + h2;
                LinearLayout.LayoutParams vl = (LinearLayout.LayoutParams) enterpriseViewPager.getLayoutParams();
                if (enterpriseModeList.size() > 4) {
                    numColumns = 4;
                    vl.height = 2 * height;
                    enterpriseViewPager.setLayoutParams(vl);
                } else {
                    numColumns = enterpriseModeList.size();
                    vl.height = height;
                    enterpriseViewPager.setLayoutParams(vl);
                }
                LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
                LinearLayout.LayoutParams param2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
                viewList.clear();
                for (int index = 0; index < pageCount; index++) {
                    //每个页面都inflate出一个新实例
                    MultiGridView multiGridView = (MultiGridView) LayoutInflater.from(bActivity).inflate(R.layout.item_enterprise_vp, null);
                    multiGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
                    multiGridView.setNumColumns(numColumns);
                    final int finalIndex = index;
                    multiGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Intent intent = new Intent(bActivity, EnterpriseModelContentActivity.class);
                            intent.putExtra("modelId", enterpriseModeList.get(i + ENTERPRISE_PAGE_SIZE * finalIndex).getModuleId());
                            intent.putExtra("modelName", enterpriseModeList.get(i + ENTERPRISE_PAGE_SIZE * finalIndex).getModuleName());
                            bActivity.startActivity(intent);
                        }
                    });
                    CategroyGridViewAdapter entranceAdapter = new CategroyGridViewAdapter(bActivity, enterpriseModeList, index, ENTERPRISE_PAGE_SIZE);
                    multiGridView.setAdapter(entranceAdapter);
                    viewList.add(multiGridView);
                }
                catAdapter.notifyDataSetChanged();
            }

            @Override
            public Type getType() {
                return new TypeToken<List<RegionModuleBean>>() {
                }.getType();
            }
        });
    }

    //获取最新十条资讯列表
    private void qryTopContentList() {
        NewActionHelp.qryTopContentList(bActivity, 10, new ObjectHttpResponseHandler<Map<String, List<RegionContentItemBean>>>() {
            @Override
            public void onFailure(int result, Header[] headers, String s, Throwable throwable) {
                final String errMsg = ResultCode.getResultText(result);
                Log.e("qryTopContentList", "errMsg" + errMsg);
                isLastSuccess = false;
                refreshView.onRefreshComplete();
            }

            @Override
            public void onSuccess(int i, Header[] headers, Map<String, List<RegionContentItemBean>> stringListMap, String s) {
                Log.e("qryTopContentList", "qryTopContentList" + stringListMap.toString());
                if (stringListMap.isEmpty() || stringListMap.size() == 0) {
                    return;
                }
                isLastSuccess = true;
                refreshView.onRefreshComplete();
                topContentList.clear();
                topContentList.addAll(stringListMap.get("modelContentList"));
                adapter.notifyDataSetChanged();
            }

            @Override
            public Type getType() {
                return new TypeToken<Map<String, List<RegionContentItemBean>>>() {
                }.getType();
            }
        });
    }

    /**
     * 跳转到图文详情页
     *
     * @param url
     */
    private void gotoImageTextActivity(String url, String title, String contentDetailId) {
        Intent intent = new Intent(bActivity, ImageTextActivity.class);
        intent.putExtra(DefaultConsts.req_url_s, url);
        intent.putExtra(DefaultConsts.title_s, title);
        intent.putExtra(DefaultConsts.COMMENT_TARGET_TYPE, "2");
        intent.putExtra(DefaultConsts.COMMENT_TARGET_VALUE, contentDetailId);
        bActivity.startActivity(intent);
    }

    /**
     * 视频资讯的详情页
     */
    private void gotoVideoDetailActivity(RegionContentItemBean contentItemBean) {
        Intent intent = new Intent(bActivity, VideoDetailActivity.class);
        intent.putExtra("video", contentItemBean);
        bActivity.startActivity(intent);
    }

    /**
     * 跳转到查看图集的页面
     * <p>
     * 1 为直接进入查看, 2 为可能要进入到瀑布流页面
     */
    private void gotoImageViewerActivity(RegionContentItemBean contentItem) {
        int imgCounts = 0;
        ImageCollection imageSet = contentItem.getImageSet();
        imgCounts = imageSet.getImageCollectionNum();
        Intent intent;
        if (imgCounts == 0) {
            Toast.makeText(bActivity, "图集已下架", Toast.LENGTH_SHORT).show();
            return;
        }
        if (/*type == 1 || ( type == 2 && */imgCounts <= IMAGE_COUNT/*) */) {
            //直接进入看图片
            intent = new Intent(bActivity, AtlasSeeActivity.class);
            intent.putExtra(AtlasSeeActivity.FROM_TYPE, DefaultConsts.TAG_FROM_ENTERPRISE);
            intent.putExtra(AtlasSeeActivity.IMAGE_COUNT, imgCounts);
        } else {//进入到瀑布流页面
            intent = new Intent(bActivity, AtlasActivity.class);
            intent.putExtra(AtlasActivity.ATLAS_NAME, imageSet.getTitle());
        }
        //todo  设置图集的数据
        intent.putExtra(AtlasActivity.ATLAS_ID, imageSet.getImageCollectionId());
        bActivity.startActivity(intent);
    }

    public int dp2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }
}
